package test.orwapkg;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeObject {
		
	public static void main(String arg[]){
		Major major = new Major();
		major.setMajorNo("123");
		major.setName("Ibn Sina");
		major.setDegree("BSc");
		major.setBuildingCode("1st Building");
		
		try {
			//define and initialize ObjectStream
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\object.data"));
			//writing major object(serializable class) to a file  
			oos.writeObject(major);
			oos.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//deserilizing object
		ObjectInputStream ois;
		try {
			ois = new ObjectInputStream(new FileInputStream("D:\\object.data"));
			Object obj = ois.readObject();
			if ( (obj != null) && (obj instanceof Major) ) {
				Major savedMajor = (Major)obj;
				System.out.println("Major No:" + savedMajor.getMajorNo());
				System.out.println("Name:" + savedMajor.getName());
				System.out.println("Degree:" + savedMajor.getDegree());
				//building code will print null bcoz it's defined as transient
				System.out.println("BuildingCode:" + savedMajor.getBuildingCode());
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
